let lastOpenTabArr = new Array(),//上一次打开的tab页
    tabLi = '#tabList li',mainIframe = '#mainFrame iframe', iframeH = getIframeHeight();
    //获取图表中的默认grid配置
lastOpenTabArr.push('homeTab');
jQuery(function ($) {
    $('#homeDiv').css('height', iframeH);
    $(tabLi).click(function () {
        topTabClickDeal(this);
    });
    initLoginInfo();
    initAllMenu();
    initOrderTotalMap();
    initOrderTotal();
    initAppUserTotal();
});

/**
 * 初始化顶部数据
 */
function initLoginInfo() {
    $.ajax({
        type: "POST",
        url: '/main/getLoginInfo',
        dataType:'json',
        cache: true,
        success: function(topData){
            $('.user-info').html('<small>Welcome,</small>' + topData.showName);
        }
    });
}
/**
 * 初始化所有的菜单
 */
function initAllMenu() {
    let menuStr = '',defaultIcon = 'menu-icon fa fa-desktop';
    $.ajax({
        type: "POST",
        url: '/menu/listAllMenu',
        dataType:'json',
        cache: true,
        success: function(menuData){
            for (let g = 0; g < menuData.length; g ++){
                let m = menuData[g];
                menuStr += '<li class="one-level"><a href="javascript:void(0);" class="dropdown-toggle">' +
                    '<i class="menu-icon ' + (isNull(m.menuIcon) ? defaultIcon : m.menuIcon) + '"></i><span class="menu-text">' + m.menuName + '</span>' +
                    '<b class="arrow fa fa-angle-down"></b></a><b class="arrow"></b>' +
                    getChildrenMenuStr(m.childrenMenuList) + '</li>';
            }
            $('#leftMenu').append(menuStr);
            //一级菜单点击事件
            menuClick('#leftMenu .one-level');
            //二级菜单点击事件
            menuClick('#leftMenu .submenu li');
        }
    });
}

/**
 * 获取子菜单字符串
 * @param childrenMenuList 子菜单集
 */
function getChildrenMenuStr(childrenMenuList){
    if (childrenMenuList == null || childrenMenuList.length < 1){
        return '';
    }
    var childrenStr = '<ul class="submenu">';
    for(let g = 0; g < childrenMenuList.length; g ++){
        let childrenMenu = childrenMenuList[g];
        let icon = isNull(childrenMenu.menuIcon) ? '' : '<i class="cm-icon ' + childrenMenu.menuIcon + '"></i>';
        childrenStr += '<li id="menu' + childrenMenu.menuId + '" data-url="' + childrenMenu.menuUrl + '">' +
        '   <a href="#">' +
        '       <i class="menu-icon fa fa-caret-right"></i>' + icon + childrenMenu.menuName +
        '   </a><b class="arrow"></b>' +
        '</li>';
    }
    return childrenStr + '</ul>';
}

/**
 * 一、二级菜单点击事件处理
 */
function menuClick(li) {
    //给被点击的二级菜单添加active class
    $(li).click(function () {
        $(li).removeClass('active');
        $(this).addClass('active');
        //如果不是2级菜单
        if (li.indexOf('submenu') < 1){
            return;
        }
        addTab(this);
    });
}

/**
 * 添加tab标签
 * @param menuObj 菜单对象
 */
function addTab(menuObj) {
    let menuId = $(menuObj).attr('id').replace('menu',''),existsTab = false,
    menuName = $(menuObj)[0].innerText,menuUrl = $(menuObj)[0].dataset.url;
    let newTabId = 'tab' + menuId;
    $('#tabList li').each(function () {
        var tabId = $(this).attr('id');
        if ($(this).hasClass('active')) {
            //先删除存在的，然后再重新添加
            arrayRemoveItem(lastOpenTabArr,tabId);
            lastOpenTabArr.push(tabId);
        }
        $(this).removeClass('active');
        //如果该菜单对应的tab已经打开
        if (tabId == newTabId){
            existsTab = true;
        }
    });
    if (existsTab){
        //激活已打开的tab
        $('#' + newTabId).addClass('active');
        //显示对应的iframe标签
        topTabClickDeal($('#' + newTabId)[0]);
        return;
    }
    $('#homeDiv').hide();
    $('#tabList').append('<li role="presentation" id="' + newTabId + '" aria-ajax="true" class="active">' +
    '   <a href="#" aria-controls="tab_mail1" role="tab" data-toggle="tab">' + menuName+ '</a>' +
    '   <i onclick="closeTab(' + menuId + ')" class="close-tab glyphicon glyphicon-remove"style="display: none;"></i>' +
    '</li>');
    $(mainIframe).hide();
    $('#mainFrame').append('<iframe id="iframe' + menuId + '" style="min-height: ' + iframeH + 'px;" class="main-frame" width="100%" height="100%" frameborder="0" src="' + menuUrl + '"></iframe>');
    $(tabLi).click(function () {
        topTabClickDeal(this);
    });
}

/**
 * 关闭tab
 * @param menuId 菜单ID
 */
function closeTab(menuId) {
    let tabId = 'tab' + menuId;
    let currTabIsActive = $('#' + tabId).hasClass('active');
    $('#iframe' + menuId + ',#' + tabId).remove();
    arrayRemoveItem(lastOpenTabArr,tabId);
    //如果被关闭的tab未激活
    if (!currTabIsActive){
        return;
    }
    $('#leftMenu li').removeClass('active');
    let lastOpenTab = lastOpenTabArr[lastOpenTabArr.length - 1];
    //如果上次打开的是主页
    if (lastOpenTab == 'homeTab'){
        $('#' + lastOpenTab).addClass('active');
        $('#homeDiv').show();
        return;
    }
    $('#' + lastOpenTab).addClass('active');
    let lastMenuId = lastOpenTab.replace('tab','');
    $('#iframe' + lastMenuId).show();
    closeMenu($('#menu' + menuId));
    openMenu($('#menu' + lastMenuId));
}

/**
 * 顶部tab点击处理事件
 * @param liObj 顶部tab li对象
 */
function topTabClickDeal(liObj) {
    //如果是主页，则隐藏其它所有的iframe
    let liId = liObj.id;
    if (liId == 'homeTab'){
        $(mainIframe).hide();
        $('#homeDiv').show();
        return;
    }
    let menuId = liId.replace('tab','');
    $(mainIframe).each(function () {
        $('#homeDiv').hide();
        if (this.id == ('iframe' + menuId)){
            $(this).show();
        } else {
            $(this).hide();
        }
    });
    let needCloseMenuId;
    $('.submenu li').each(function () {
        if ($(this).hasClass('active')){
            needCloseMenuId = $(this).attr('id');
        }
    });
    closeMenu($('#' + needCloseMenuId));
    openMenu($('#menu' + menuId));
}
let geoCoordMap = {
    '北京':[116.4,39.91],
    '长沙':[112.92,28.25]
};

/**
 * 展开一级菜单
 * @param menuObj 要展开的二级菜单对象
 */
function openMenu(menuObj) {
    menuObj.addClass('active');
    menuObj.parent().addClass('nav-show').show();
    menuObj.parent().parent().addClass('open active');
}

/**
 * 关闭一级菜单
 * @param menuObj 要关闭的二级菜单对象
 */
function closeMenu(menuObj) {
    menuObj.removeClass('active');
    //处理菜单的父级标签ul class = submenu nav-show
    menuObj.parent().removeClass('nav-show').hide();
    //处理菜单的爷级标签，即对应的1级菜单:li class = one-level open active
    menuObj.parent().parent().removeClass('open active');
}
/**
 * 初始化各城市的订单总量地图
 */
function initOrderTotalMap() {
    $.ajax({
        type: "POST",
        url: '/main/listCityOrderTotal',
        dataType:'json',
        cache: true,
        success: function(cityOrderData){
            drawOrderTotalMap(cityOrderData);
        }
    });
}
function convertData(data) {
    let res = [];
    for (let i = 0; i < data.length; i ++) {
        let geoCoord = geoCoordMap[data[i].name];
        if (geoCoord) {
            res.push({
                name: data[i].name,
                value: geoCoord.concat(data[i].value)
            });
        }
    }
    return res;
};

/**
 * 各城市的订单总量地图
 * @param cityTotalArr 各城市的订单总量数据数组
 */
function drawOrderTotalMap(cityTotalArr) {
    let option = {
        title: {
            text: '全国主要城市订单量',
            left: 'center'
        },
        tooltip : {
            trigger: 'item'
        },
        /*加载 amap 组件
          说明：如果想要添加卫星、路网等图层,暂时先不要使用layers配置，因为存在Bug
          建议使用amap.add的方式，使用方式参见最下方代码,其他高德地图支持的初始配置项都可以在这里配置
        */
        amap: {
            center: [106.36, 34.36],// 高德地图中心经纬度
            zoom: 5,// 高德地图缩放
            resizeEnable: true,// 启用resize
            renderOnMoving: true// 移动过程中实时渲染 默认为true 如数据量较大 建议置为false
            //mapStyle:'amap://styles/dark'// 自定义地图样式主题
        },
        series : [
            {
                name: '订单总量',
                type: 'scatter',
                coordinateSystem: 'amap',
                data: convertData(cityTotalArr),
                symbolSize: function (val) {
                    return val[2] / 4;
                },
                encode: {
                    value: 2
                },
                label: {
                    formatter: '{b}',
                    position: 'right',
                    show: false
                },
                itemStyle: {
                    color: 'purple'
                },
                emphasis: {
                    label: {
                        show: true
                    }
                }
            },
            {
                name: '总量前5',
                type: 'effectScatter',
                coordinateSystem: 'amap',
                data: convertData(cityTotalArr.sort(function (a, b) {
                    return b.value - a.value;
                }).slice(0, 6)),
                symbolSize: function (val) {
                    return val[2] / 4;
                },
                encode: {
                    value: 2
                },
                showEffectOn: 'render',
                rippleEffect: {
                    brushType: 'stroke'
                },
                hoverAnimation: true,
                label: {
                    formatter: '{b}',
                    position: 'right',
                    show: true
                },
                itemStyle: {
                    color: 'purple',
                    shadowBlur: 10,
                    shadowColor: '#333'
                },
                zlevel: 1
            }
        ]
    };
    let thisLastTotalLine = echarts.init(I('homeDiv'));
    thisLastTotalLine.setOption(option);
    let amap = thisLastTotalLine.getModel().getComponent("amap").getAMap();
    // 下边就可以按照高德官方API随意调用了，比如添加一些控件
    amap.addControl(new AMap.Scale());
    amap.addControl(new AMap.ToolBar());
    // 添加一些图层 卫星图层/交通路网等等
    // var satelliteLayer = new AMap.TileLayer.Satellite();
    // var roadNetLayer = new AMap.TileLayer.RoadNet();
    // amap.add([satelliteLayer, roadNetLayer]);
}
/**
 * 初始化顶部的订单总量数据
 */
function initOrderTotal() {
    $.ajax({
        type: "POST",
        url: '/main/listTodayYesterdayTotal',
        dataType:'json',
        cache: true,
        success: function(tyTotalData){
            setOrderTotal(tyTotalData);
        }
    });
}

/**
 * 设置订单总量数据
 * @param tyTotalData 总量数据
 */
function setOrderTotal(tyTotalData) {
    let otObj = tyTotalData[0], moreOrLess = '少',c = 'rgba(255,255,255,0.95)', ttyObj = $('#todayThanYesterday');
    let orderTotal = otObj.orderTotal,todayTotal = otObj.todayTotal,finishOrder = otObj.finishTotal;
    let todayThanYesterday = todayTotal - otObj.yesterdayTotal;
    let finishRate = parseInt(finishOrder / orderTotal * 100);
    let idArr = ['orderTotal','orderTodayTotal','todayThanYesterday','noRobOrder','robbedOrder',
        'cancelOrder','expireOrder','finishRateValue'],
    valueArr = [orderTotal,todayTotal,todayThanYesterday,otObj.noRobTotal,otObj.robbedTotal,
    otObj.cancelTotal,otObj.expireTotal,finishRate];
    if (todayThanYesterday > 0){
        moreOrLess = '多';
        ttyObj.removeClass('stat-important').addClass('stat-success');
    }
    ttyObj.attr('title','今天比昨天'+ moreOrLess + todayThanYesterday + '单');
    for (let i = 0; i < idArr.length; i ++){
        $('#' + idArr[i]).text(valueArr[i]);
    }
    //订单完成率
    $('#finishRate').attr('data-percent',finishRate);
    //画百分比圆圈
    $('.easy-pie-chart.percentage').each(function(){
        let $box = $(this).closest('.infobox');
        let barColor = $(this).data('color') || (!$box.hasClass('infobox-dark') ? $box.css('color') : c);
        let trackColor = barColor == c ? c : '#E2E2E2';
        let size = parseInt($(this).data('size')) || 50;
        $(this).easyPieChart({
            barColor: barColor,
            trackColor: trackColor,
            scaleColor: false,
            lineCap: 'butt',
            lineWidth: parseInt(size/10),
            animate: ace.vars['old_ie'] ? false : 1000,
            size: size
        });
    });
}
/**
 * 初始化顶部的用户总数
 */
function initAppUserTotal() {
    $.ajax({
        type: "POST",
        url: '/main/listTodayYesterdayUser',
        dataType:'json',
        cache: true,
        success: function(appUserData){
            setAppUserTotal(appUserData);
        }
    });
}

/**
 * 设置用户总数
 * @param appUserData 用户数据 fa-arrow-up
 */
function setAppUserTotal(appUserData) {
    let userObj = appUserData[0], upOrDown = 'down';
    let yesterdayTotal = userObj.yesterdayTotal, todayTotal = userObj.todayTotal;
    $('#appUserTotal').text(userObj.userTotal);
    $('#userTodayTotal').text(todayTotal);
    let todayThanYesterday = todayTotal - yesterdayTotal;
    if (todayThanYesterday >= 0){
        todayThanYesterday = '+' + todayThanYesterday;
        upOrDown = 'up';
    }
    $('#userMore').attr('title','今天比昨天' + todayThanYesterday + '人');
    $('#userToadyThanYesterday').text(todayThanYesterday);
    $('#userUpDown').removeClass('fa-arrow-down').removeClass('fa-arrow-up').addClass('fa-arrow-' + upOrDown);
}